package actions.demo;

/**
 * 对于域对象的新增、修改等操作以及其他的涉及到表单提交（录入界面）的业务操作， 强烈建议采用Struts
 * 动态校验FormBean来实现基于Validator的Form字段校验、重复提交等必要功能。
 */

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

import service.OrderService;
import domain.Order;

/**
 * @author sunj
 */
public class OrderCreateAction extends Action {
    /**
     * 订单service.
     */
    private OrderService orderService = null;

    /**
     * 创建订单.
     * @param mapping action mapping
     * @param form action form
     * @param request http request
     * @param response http response
     * @return action forword
     * @throws Exception any exception
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        /**
         * 日期输入格式.
         */
        final DateFormat DATE_FAMAT = new SimpleDateFormat("yyyy-MM-dd",
                Locale.UK);
        // 验证是否是有效的Token,防止重复提交
        if (isTokenValid(request, true)) {
            DynaValidatorForm orderForm = (DynaValidatorForm) form;
            Order newOrder = new Order();
            newOrder.setProductName(orderForm.getString("productName"));
            newOrder.setCustomerName(orderForm.getString("customerName"));
            newOrder.setTotalPrice(Double.valueOf(orderForm
                    .getString("totalPrice")));
            String strDate = orderForm.getString("orderDate");
            Date date = new Date(DATE_FAMAT.parse(strDate).getTime());
            newOrder.setOrderDate(date);
            orderService.addOrder(newOrder);
            return mapping.findForward("success");
        } else {
            // 重复提交,转到重复提交失败界面
            return mapping.findForward("error.duplicateSubmit");
        }
    }

    /**
     * @param pOrderService the orderService to set
     */
    public void setOrderService(OrderService pOrderService) {
        orderService = pOrderService;
    }
}
